<template>
  <div>
    <el-card class="formcard">
      <!-- 表頭按鈕 -->
      <el-row id="topBtnRight">
        <el-button type="success" size="small" plain @click="toAddCompany">
          <Icon icon="material-symbols:add-circle-rounded" /><span>{{ $t('common.add') }}</span>
        </el-button>
        <el-button type="info" size="small" plain>
          <Icon icon="material-symbols:print" /><span>{{ $t('common.listPrint') }}</span>
        </el-button>
        <el-button type="info" size="small" plain @click="init">
          <Icon icon="tabler:refresh" /><span>{{ $t('common.refresh') }}</span>
        </el-button>
      </el-row>

      <!-- 搜索結果表格 -->
      <el-table
        :data="tableView"
        tooltip-effect="light"
        style="width: 100%; border-color: #a0cfff"
        :max-height="tableHeight"
        stripe
        class="companyList"
        :header-cell-style="{
          background: 'var(--el-color-primary-light-9)',
          color: '#409eff'
        }"
      >
        <el-table-column
          prop="userName"
          :label="$t('company.companyAccount')"
          show-overflow-tooltip
          min-width="150"
        />
        <el-table-column
          prop="licenseNo"
          :label="$t('company.licenseNo')"
          show-overflow-tooltip
          min-width="150"
        />
        <el-table-column
          prop="name"
          :label="$t('company.nameCn')"
          show-overflow-tooltip
          min-width="150"
        />
        <el-table-column
          prop="enName"
          :label="$t('company.nameEN')"
          show-overflow-tooltip
          min-width="150"
        />
        <el-table-column
          prop="telNo"
          :label="$t('company.phone')"
          show-overflow-tooltip
          min-width="150"
        />
        <el-table-column fixed="right" :label="$t('common.operation')" width="170">
          <template #default="{ row }">
            <el-button
              type="success"
              plain
              circle
              size="small"
              :title="$t('common.check')"
              @click="toLookOrEdit('look', row.tenantId)"
            >
              <el-icon>
                <View />
              </el-icon>
            </el-button>
            <el-button
              type="primary"
              plain
              circle
              size="small"
              :title="$t('common.modify')"
              @click="toLookOrEdit('edit', row.tenantId)"
            >
              <el-icon>
                <Edit />
              </el-icon>
            </el-button>
            <el-button
              type="danger"
              plain
              circle
              size="small"
              :title="$t('common.delete')"
              @click="deleteCompany(row.tenantId)"
            >
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
            <el-button
              type="warning"
              plain
              circle
              size="small"
              :title="$t('login.resetPassword')"
              @click="openDialog(row)"
            >
              <Icon icon="ph:password-bold" />
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分頁器 -->
      <div class="demo-pagination-block">
        <el-pagination
          v-model:currentPage="currentPage"
          v-model:page-size="pageSize"
          @current-change="changePage"
          @size-change="changePageSize"
          :page-sizes="pageSizes"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        />
      </div>
    </el-card>

    <!-- 重置密碼對話框 -->
    <el-dialog v-model="dialogVisible" :title="$t('login.resetPassword')" width="500px" draggable>
      <el-form ref="formRef" :model="dialogForm" :rules="dialogRule">
        <el-form-item :label="$t('login.resetPassword')" label-width="auto" prop="newPassword">
          <el-input
            v-model="dialogForm.newPassword"
            type="password"
            autocomplete="off"
            :show-password="true"
            maxlength="25"
            :placeholder="$t('login.passwordPlaceholder')"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ $t('common.cancel') }}</el-button>
          <el-button type="primary" @click="resetPsd">{{ $t('common.ok') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { reactive, toRefs, onMounted, onActivated, nextTick, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { View, Edit, Delete } from '@element-plus/icons-vue'
import { deleteCompany, companyList, updatePassword } from '@/api/company'
import { useRouter } from 'vue-router'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useCache } from '@/hooks/web/useCache'
import { getMd5Password } from '@/utils'
import { useI18n } from '@/hooks/web/useI18n'
import { Paging } from '@/config/public'

export default {
  name: 'CompanyManagement',
  components: {
    View,
    Edit,
    Delete
  },
  props: {},
  setup() {
    const router = useRouter()
    const { wsCache } = useCache()
    const { emitter } = useEmitt()
    const formRef = ref()
    const { t } = useI18n()
    const state = reactive({
      // 搜索key
      // filterKey: '',
      // 表格數據
      // tableLoading: false,
      tableData: [],
      tableView: [],
      tableHeight: 400,
      pageSizes: Paging.sizes,
      // 分頁相關屬性
      totalCount: 0,
      currentPage: 1,
      pageSize: Paging.defaultSize,
      // 对话框绑定的数据
      dialogVisible: false,
      dialogForm: {
        newPassword: '',
        userId: ''
      },
      dialogRule: {
        newPassword: [
          { required: true, message: t('login.errPasswordEmpty'), trigger: 'blur' },
          {
            pattern:
              /^[A-Za-z0-9`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]{6,25}$/,
            message: t('login.errPasswordFormat'),
            trigger: ['blur', 'change']
          }
        ]
      }
    })
    onMounted(async () => {
      init()
      nextTick(() => {
        state.tableHeight = window.innerHeight - 300
        // 监听浏览器高度变化
        window.onresize = () => {
          state.tableHeight = window.innerHeight - 300
        }
      })
    })
    useEmitt({
      //刷新列表事件
      name: 'refreshCompanyList',
      callback: () => {
        init()
      }
    })
    onActivated(async () => {})
    const methods = {
      changePage(page) {
        state.currentPage = page
        init()
      },
      changePageSize(pageSize) {
        state.pageSize = pageSize
        state.currentPage = 1
        init()
      },
      // 添加公司跳轉
      toAddCompany() {
        wsCache.set('companyStatus', null)
        wsCache.set('companyId', null)
        emitter.emit('editCompany', 'add')
        router.push({ name: 'EditCompany' })
      },
      // 詳情頁/修改頁跳轉
      toLookOrEdit(type, id) {
        wsCache.set('companyStatus', type)
        wsCache.set('companyId', id)
        emitter.emit('editCompany', type)
        router.push({ name: 'EditCompany' })
      },
      // 刪除公司
      deleteCompany(id) {
        ElMessageBox.confirm(t('common.delMessage'), t('common.warning'), {
          confirmButtonText: t('common.ok'),
          cancelButtonText: t('common.cancel'),
          type: 'warning'
        })
          .then(async () => {
            await deleteCompany({ tenantId: id })
            init()
          })
          .catch(() => {})
      },
      // 重置密碼
      openDialog(row) {
        state.dialogForm.newPassword = row.password
        state.dialogForm.userId = row.userId
        state.dialogVisible = true
        // formRef.value.clearValidate()
      },
      resetPsd() {
        formRef.value.validate(async (vaild) => {
          if (vaild) {
            let form = Object.assign({}, state.dialogForm)
            form.newPassword = getMd5Password(form.newPassword)
            await updatePassword(form).then((res) => {
              if (res) {
                state.dialogVisible = false
                init()
                ElMessage.success(t('user.updPasswordSuccess'))
              }
            })
          }
        })
      }
    }

    //渲染页面的接口
    const init = async () => {
      // state.tableLoading = true
      await companyList({
        pageNo: state.currentPage,
        pageSize: state.pageSize,
        params: {
          'Q_c.status_S_NEQ': 'deleted'
        },
        sortField: '',
        sortOrder: ''
      })
        .then((res) => {
          state.tableView = res.result.data
          state.totalCount = res.result.totalCount
        })
        .catch(() => {
          // state.tableLoading = false
        })
    }
    return {
      ...toRefs(state),
      formRef,
      init,
      ...methods
    }
  }
}
</script>

<style lang="less" scoped>
// 搜索卡片樣式
.box-card {
  margin-top: -12px;
}

:deep(.el-card__header) {
  border-bottom: 0;
  box-sizing: border-box;
}

//搜索條樣式
.input-with-select {
  width: 50%;
  margin-left: auto;
  margin-right: auto;
}

:deep(.el-input-group__append) {
  background-color: #ecf5ff;
  border-color: #a0cfff;
  color: #409eff;
  box-shadow: #409eff;
  cursor: pointer;
}

:deep(.el-input-group__append):hover {
  background-color: #ecf5ff;
  border-color: #409eff !important;
  color: #409eff;
  box-shadow: #409eff;
  cursor: pointer;
}

:deep(.el-input) {
  border-color: #a0cfff;
  font-size: 12px;
}

// 公司列表樣式
.companyList {
  font-size: 12px;
}

// 分頁器樣式
.demo-pagination-block {
  display: flex;
  justify-content: center;
  justify-items: center;
  margin-top: 20px;
  margin-bottom: 20px;
}

:deep(.el-pagination__sizes > .el-select) {
  margin-top: -3px;
}
:deep(.el-pager li) {
  font-size: 12px;
  height: 28px;
  margin-top: -1px;
}
:deep(.el-pagination span:not([class*='suffix'])) {
  font-size: 12px;
}
</style>
